﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Configuration;

namespace UpdateApp
{
    /// <summary>
    /// 公用类，如果无法调用，右键该文件 >> 属性 >> 生成操作 >> 编译
    /// </summary>
    public class Common
    {
        private static Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        public static void ChangeConfig(string val)
        {
            //config.AppSettings.Settings.Remove("isSave");
            //config.AppSettings.Settings.Add("isSave", val);
            config.AppSettings.Settings["isSave"].Value = val;

            int minute;
            if (int.TryParse(val, out minute))
                config.AppSettings.Settings["ExpirationTime"].Value = DateTime.Now.AddMinutes(minute).ToString();
            else
                config.AppSettings.Settings["ExpirationTime"].Value = "";

            config.Save();

            SaveLog("修改上传时间「" + val + "」");
        }

        public static void ChangeIpConfig(string val)
        {
            string IpList = ConfigurationManager.AppSettings["IPList"];

            var ips = IpList != null ? IpList.Split('|').ToList<string>() : new List<string>();

            if (!ips.Contains(val))
            {
                ips.Add(val);

                SaveLog("设置白名单「" + val + "」", true);
            }
            else
            {
                ips.Remove(val);

                SaveLog("移除白名单「" + val + "」", true);
            }

            // Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //修改配置节点
            config.AppSettings.Settings["IPList"].Value = string.Join("|", ips);

            config.Save();
        }

        public static void ChangeAppConfig(string val, string fileName, bool isDel = false)
        {
            string[] arr = val.Split('/');

            string name = arr.Length > 0 ? arr[0] : "";
            string path = arr.Length > 1 ? arr[1] : "";

            if (string.IsNullOrEmpty(name))
                return;

            config.AppSettings.Settings.Remove(name);
            config.AppSettings.Settings.Remove(name + "Path");

            if (!isDel)
            {
                config.AppSettings.Settings.Add(name, path);
                config.AppSettings.Settings.Add(name + "Path", "Download//" + name + "//" + path + "//" + fileName);
            }

            config.Save();
        }

        public static bool CheckUserHost()
        {
            string list = ConfigurationManager.AppSettings["IPList"];
            string strTime = ConfigurationManager.AppSettings["ExpirationTime"];

            if (list == string.Empty)
                return true;

            string userIP = Common.IP;

            //本地IP
            if (userIP.Length < 5)
                return true;

            //SaveLog("校验IP");

            DateTime time;
            if (DateTime.TryParse(strTime, out time))
                if (DateTime.Now <= time)
                    return true;
                else
                    ChangeConfig("");   //如果超时 清除isSave，不允许非白名单上传，不记录日志

            foreach (var item in list.Split('|'))
            {
                if (string.IsNullOrWhiteSpace(item))
                    continue;

                if (userIP.StartsWith(item))
                    return true;

            }

            return false;
        }

        public static string IP
        {
            get
            {
                string userIP;
                HttpRequest Request = HttpContext.Current.Request; // 如果使用代理，获取真实IP  
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    userIP = Request.ServerVariables["REMOTE_ADDR"];
                else
                    userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (userIP == null || userIP == "")
                    userIP = Request.UserHostAddress;
                return userIP;
            }
        }

        //保存日志
        public static void SaveLog(string message, bool isRoot = false)
        {
            try
            {
                //string isSave = ConfigurationManager.AppSettings["isSave"];

                //if (!string.IsNullOrEmpty(isSave))
                //{
                string dir = isRoot ? FileHelper.GetUploadPath() : Path.Combine(FileHelper.GetUploadPath(), DateTime.Now.ToString("yyyy-MM-dd"));
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                var log = Path.Combine(dir, "Info.log");

                message = DateTime.Now.ToLocalTime().ToString() + ":「" + Common.IP + "」" + message + "\r\n\r\n";

                StreamWriter sw = new StreamWriter(log, true, Encoding.Default);
                sw.Write(message);

                sw.Close();
                //}
            }
            catch (System.Exception e)
            {

            }
        }

        public static void SaveFile(string title, string content, string type, string folder = null)
        {
            try
            {
                folder = folder ?? DateTime.Now.ToString("yyyy-MM-dd");
                string dir = Path.Combine(FileHelper.GetUploadPath(), folder);

                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                var file = Path.Combine(dir, title + type);

                StreamWriter sw = new StreamWriter(file, false, file.EndsWith(".ini", true, null) ? Encoding.Unicode : Encoding.Default);

                sw.Write(content);

                sw.Close();
            }
            catch (System.Exception e)
            {

            }
        }
    }

    public class TransApi
    {
        private static string TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}";

        private string appid;
        private string securityKey;

        public TransApi(string appid, string securityKey)
        {
            this.appid = appid;
            this.securityKey = securityKey;
        }

        public string GetTransResult(string query, string from, string to)
        {
            string q = System.Web.HttpUtility.UrlEncode(query, System.Text.Encoding.UTF8);
            Random rnd = new Random();
            string salt = rnd.Next().ToString();

            string sign = GetMD5(appid + query + salt + securityKey);

            string address = string.Format(TRANS_API_HOST, q, from, to, appid, salt, sign);

            HttpWebRequest request;
            request = (HttpWebRequest)HttpWebRequest.Create(address);
            request.Method = "GET";
            request.ProtocolVersion = HttpVersion.Version11;
            //request.Connection = "keep-alive";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Timeout = 10000;
            //request.Headers.Add("Connection", "keep-alive"); 

            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.CookieContainer = new CookieContainer();

            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            Stream st;
            st = response.GetResponseStream();
            GZipStream temp = null;
            StreamReader stReader;
            if (response.ContentEncoding.ToLower().Contains("gzip"))
            {
                temp = new GZipStream(st, CompressionMode.Decompress, true);
                stReader = new StreamReader(temp, Encoding.Default);
            }
            else
            {
                stReader = new StreamReader(st, Encoding.Default);
            }

            string text;
            text = stReader.ReadToEnd();

            stReader.Close();
            if (temp != null)
                temp.Close();
            st.Close();

            BaiduResult r = JsonGet(text);
            if (r != null && r.trans_result != null && r.trans_result.Length > 0)
                return r.trans_result[0].dst;
            else
                return "";
        }

        /// <summary>  
        /// 加密成32位小写的MD5  
        /// </summary>  
        /// <param name="myString">传入需要加密的字符串</param>  
        /// <returns>返回加密后的字符串</returns>  
        public static string GetMD5(string myString)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(myString, "MD5").ToLower();
        }

        public static BaiduResult JsonGet(string jsonString)
        {
            if (jsonString.Length > 0)
            {
                var ms = new MemoryStream(Encoding.Default.GetBytes(jsonString));
                return (BaiduResult)new DataContractJsonSerializer(typeof(BaiduResult)).ReadObject(ms);
            }
            return null;
        }

    }

    public class BaiduResult
    {
        [DataMember(Order = 0, IsRequired = true)]
        public string from;
        [DataMember(Order = 1)]
        public string to;
        public class Trans_result
        {
            public string src;
            public string dst;
        }
        [DataMember(Order = 2)]
        public Trans_result[] trans_result;
    }
}